<?php

class updateLatAndLng
{
       public static $_instance = null;

       public static function instance()
       {
           if( is_null( self::$_instance ))
           {
               self::$_instance = new static();
           }
           return self::$_instance;
       }

       public  function update()
       {
           //获取没更新经纬度的数据
            $orders = Db::instance()->table('tb_order')
                ->where([
                  //  ['Day',date('Y-m-d')],
                    ['isUpdateLatAndLng',0]
                ])
                ->get()
                ->first();

            if($orders)
            {

                $orders = $orders->toArray();
                $latAndLng = $this->getLatlng($orders['Address'].','.$orders['City'].','.$orders['Region']);
                 Db::instance()->update('tb_order',[
                    'lat'=>$latAndLng['lat'],
                    'lng'=>$latAndLng['lng'],
                    'isUpdateLatAndLng'=>1,
                     'positionStatus'=>1
                   ],[
                       ['id',$orders['id']]
                ]);
                echo 'Updated! [ '.$orders['id'].' ]'.PHP_EOL;

            }


       }
    protected function getLatlng($url){
        $url = str_replace(' ','+' ,$url);
        $url = "https://maps.googleapis.com/maps/api/geocode/json?address=".$url."&key=".Config::GOOGLE_MAP_API_KEY;
        $res = Http::instance()->request( $url , 'post')->data();
        $res = json_decode($res , true);
        if( $res['status']=='OK') {
            return $res['results']['0']['geometry']['location'];
        }else{
            return ['lat'=>'0','lng'=>'0'];
        }
    }
}